package core.reactor;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import config.mm_config;
import context.mm_context;
import log.mm_logger;
import utils.mm_thread;

/**
 * 启动器
 * @author dongyazhuo
 */
public class mm_start {

	private String TAG = mm_start.class.getSimpleName() + " : ";

	private volatile static mm_start _instance = null;

	public static Map<mm_config, mm_reactor> mm_reactor_group = new HashMap<mm_config, mm_reactor>();

	private mm_start() {

	}

	static public mm_start instance() {
		if (null == _instance) {
			synchronized (mm_start.class) {
				if (null == _instance) {
					_instance = new mm_start();
				}
			}
		}
		return _instance;
	}

	/**
	 * 根据现有配置文件，启动全部反应器
	 */
	public void do_work() {
		Collection<mm_config> values = mm_context.instance().get_configs().values();
		for (mm_config _mm_config : values) {
			start(_mm_config);
			mm_thread.sleep(200L);
		}
		mm_logger.i(TAG + " start ok !!! ");
	}

	/**
	 * 根据配置文件启动一组反应器
	 * @param _mm_config
	 */
	public void start(mm_config _mm_config) {
		if (_mm_config.isStart()) {
			mm_reactor _mm_reactor = new mm_reactor(_mm_config);
			new mm_thread().start(_mm_reactor);
			mm_reactor_group.put(_mm_config, _mm_reactor);
		}
	}

	/**
	 * 关闭一组反应器
	 * @param _mm_reactor
	 */
	public static void stop(mm_reactor _mm_reactor) {
		Thread current_thread = Thread.currentThread();
		if (null != _mm_reactor.login_guard_thread && current_thread != _mm_reactor.login_guard_thread.get_thread()) {
			_mm_reactor.login_guard_thread.stop();
		}
		if (null != _mm_reactor.mm_query_thread && current_thread != _mm_reactor.mm_query_thread.get_thread()) {
			_mm_reactor.mm_query_thread.stop();
		}
		mm_reactor_group.remove(_mm_reactor._mm_config);
		current_thread.stop();

	}

}
